package cn.laowen.basic.controller;

import cn.laowen.basic.exception.BusinessException;
import cn.laowen.basic.util.AjaxResult;
import cn.laowen.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 分布式文件接口
 * 1.上传接口
 *
 * 2.删除接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 1.文件上传接口
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            String filename = file.getOriginalFilename();//获取文件全路径   /aaa/bbb/ccc/1.jpg
            String extName = filename.substring(filename.lastIndexOf(".") + 1);//截取最后一个点的位置+1,获取后缀  jpg
            String path = FastdfsUtil.upload(file.getBytes(),extName);//返回一个相对路径path
            return AjaxResult.me().setResultObj(path);
        } catch (BusinessException e) {//业务异常
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }

    /**
     * 2.文件删除接口
     * @param path
     * @return
     */
    @DeleteMapping //  http://localhost:8080/fastDfs?path=/group1/M00/00/07/CgAIC2KmGNOAGRV9AAgpKd7_gdo105.jpg
    public AjaxResult delete(@RequestParam String path){
        try {
            String pathTmp = path.substring(1);//不要前面第一个/,  group1/M00/00/04/CgAIC2Kln6SAEh72AAD1vLo2Ruw09.jpeg
            String group = pathTmp.substring(0,pathTmp.indexOf("/"));//接着截取从0到第一个/位置,  group1
            //截取第一个斜杠后的位置,含前不含后()  M00/00/04/CgAIC2Kln6SAEh72AAD1vLo2Ruw09.jpeg
            String filename = pathTmp.substring(pathTmp.indexOf("/")+1);
            FastdfsUtil.delete(group,filename);
            return AjaxResult.me();
        } catch (BusinessException e) {//业务异常
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }



}
